import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { 
  ArrowLeft, User, Settings, Download, 
  CheckCircle, Clock, Target, Award,
  Smartphone, Bell, HelpCircle, LogOut
} from 'lucide-react'
import { taskAPI, statsAPI } from '../services/api'
import { useAuth } from '../contexts/AuthContext'
import { getVersionString } from '../utils/version'

interface UserStats {
  totalTasks: number
  completedTasks: number
  pendingTasks: number
  completionRate: number
  streakDays: number
  totalCategories: number
}

export default function ProfilePage() {
  const navigate = useNavigate()
  const { user, logout } = useAuth()
  const [userStats, setUserStats] = useState<UserStats>({
    totalTasks: 0,
    completedTasks: 0,
    pendingTasks: 0,
    completionRate: 0,
    streakDays: 0,
    totalCategories: 0
  })
  const [isLoading, setIsLoading] = useState(true)

  // 处理登出
  const handleLogout = async () => {
    if (confirm('确定要退出登录吗？')) {
      await logout()
      navigate('/login', { replace: true })
    }
  }

  useEffect(() => {
    loadUserStats()
  }, [])

  const loadUserStats = async () => {
    try {
      setIsLoading(true)
      
      // 获取任务统计和连续天数
      const [tasks, streakResult] = await Promise.all([
        taskAPI.getAllTasks(),
        statsAPI.getStreak()
      ])
      
      const completedCount = tasks.filter((task: any) => task.completed).length
      const totalCount = tasks.length
      const pendingCount = totalCount - completedCount
      const completionRate = totalCount > 0 ? (completedCount / totalCount) * 100 : 0
      
      // 获取实际连续完成天数
      const streakDays = streakResult.success ? streakResult.data.currentStreak : 0
      
      // 计算使用的分类数量
      const categories = new Set(tasks.map((task: any) => task.category))
      
      setUserStats({
        totalTasks: totalCount,
        completedTasks: completedCount,
        pendingTasks: pendingCount,
        completionRate: Math.round(completionRate),
        streakDays,
        totalCategories: categories.size
      })
    } catch (error) {
      console.error('加载用户统计失败:', error)
    } finally {
      setIsLoading(false)
    }
  }

  const handleExportData = async () => {
    try {
      const tasks = await taskAPI.getAllTasks()
      const dataStr = JSON.stringify(tasks, null, 2)
      const dataBlob = new Blob([dataStr], { type: 'application/json' })
      
      const url = URL.createObjectURL(dataBlob)
      const link = document.createElement('a')
      link.href = url
      link.download = `aide-tasks-${new Date().toISOString().split('T')[0]}.json`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
    } catch (error) {
      console.error('导出数据失败:', error)
    }
  }

  const menuItems = [
    {
      icon: Settings,
      title: '应用设置',
      subtitle: '主题、语言、数据管理等',
      onClick: () => navigate('/settings'),
      color: 'text-blue-600 bg-blue-50'
    },
    {
      icon: Download,
      title: '导出数据',
      subtitle: '备份您的所有任务数据',
      onClick: handleExportData,
      color: 'text-orange-600 bg-orange-50'
    },
    {
      icon: Bell,
      title: '通知设置',
      subtitle: '管理提醒和通知',
      onClick: () => navigate('/notifications'),
      color: 'text-amber-600 bg-amber-50'
    },
    {
      icon: Smartphone,
      title: '安装应用',
      subtitle: '将AIDE添加到主屏幕',
      onClick: () => {
        // 检查是否已经是PWA环境
        if (window.matchMedia('(display-mode: standalone)').matches) {
          alert('✅ AIDE已经安装为桌面应用！')
          return
        }
        
        // 检查是否支持PWA安装
        if ('serviceWorker' in navigator) {
          alert('💡 在浏览器地址栏中点击安装图标，或在菜单中选择"安装AIDE"即可将应用添加到桌面。安装后可以像普通软件一样使用！')
        } else {
          alert('您的浏览器不支持PWA安装功能，请使用Chrome、Edge或Firefox等现代浏览器。')
        }
      },
      color: 'text-indigo-600 bg-indigo-50'
    },
    {
      icon: HelpCircle,
      title: '帮助与反馈',
      subtitle: '使用指南和问题反馈',
      onClick: () => navigate('/help'),
      color: 'text-green-600 bg-green-50'
    },
    {
      icon: LogOut,
      title: '退出登录',
      subtitle: '安全退出当前账号',
      onClick: handleLogout,
      color: 'text-red-600 bg-red-50'
    }
  ]

  const statsCards = [
    {
      icon: CheckCircle,
      title: '已完成',
      value: userStats.completedTasks,
      color: 'text-green-600 bg-green-50 border-green-200'
    },
    {
      icon: Clock,
      title: '待完成',
      value: userStats.pendingTasks,
      color: 'text-blue-600 bg-blue-50 border-blue-200'
    },
    {
      icon: Target,
      title: '完成率',
      value: `${userStats.completionRate}%`,
      color: 'text-purple-600 bg-purple-50 border-purple-200'
    },
    {
      icon: Award,
      title: '连续天数',
      value: `${userStats.streakDays}天`,
      color: 'text-orange-600 bg-orange-50 border-orange-200'
    }
  ]

  return (
    <div className="min-h-screen bg-theme-bg-secondary">
      {/* Header */}
      <header className="sticky top-0 bg-theme-bg/95 backdrop-blur-sm shadow-sm border-b border-theme-border/60 z-10">
        <div className="flex items-center justify-between px-4 py-3 max-w-md mx-auto sm:max-w-lg md:max-w-xl lg:max-w-2xl xl:max-w-4xl">
          <button
            onClick={() => navigate('/')}
            className="p-2 text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-lg transition-all touch-manipulation"
          >
            <ArrowLeft size={20} />
          </button>
          <h1 className="text-lg font-semibold text-theme-text">个人中心</h1>
          <div className="w-9 h-9" /> {/* 占位符保持居中 */}
        </div>
      </header>

      <main className="px-4 pb-6 space-y-4 max-w-md mx-auto sm:max-w-lg md:max-w-xl lg:max-w-2xl xl:max-w-4xl">
        {/* 用户信息卡片 */}
        <div className="bg-theme-bg rounded-2xl border border-theme-border/60 p-5 shadow-sm mt-4">
          <div className="flex items-center gap-4">
            <div className="w-16 h-16 bg-gradient-to-br from-blue-500 to-blue-600 rounded-2xl flex items-center justify-center">
              <User size={28} className="text-white" />
            </div>
            <div className="flex-1">
              <h2 className="text-lg font-semibold text-theme-text">
                {user?.username || user?.email?.split('@')[0] || '用户'}
              </h2>
              <p className="text-sm text-theme-text-muted">
                {user?.email || user?.phone || '未设置'}
              </p>
              <div className="flex items-center gap-2 mt-1">
                <span className="px-2 py-0.5 bg-blue-100 text-blue-700 text-xs font-medium rounded-full">
                  {user?.login_type === 'email' ? '邮箱用户' : user?.login_type === 'phone' ? '手机用户' : '用户'}
                </span>
                <span className="text-xs text-slate-400">
                  加入于 {new Date(user?.created_at || '').getFullYear()}年
                </span>
              </div>
            </div>
          </div>
        </div>

        {/* 数据概览 */}
        <div className="bg-theme-bg rounded-2xl border border-theme-border/60 p-5 shadow-sm">
          <div className="flex items-center gap-2 mb-4">
            <div className="w-1 h-5 bg-gradient-to-b from-green-500 to-green-600 rounded-full"></div>
            <h3 className="text-sm font-semibold text-theme-text">数据概览</h3>
          </div>
          
          {isLoading ? (
            <div className="grid grid-cols-2 gap-3">
              {[1, 2, 3, 4].map(i => (
                <div key={i} className="p-3 bg-theme-bg-secondary rounded-xl animate-pulse">
                  <div className="w-6 h-6 bg-slate-200 rounded-lg mb-2"></div>
                  <div className="w-12 h-4 bg-slate-200 rounded mb-1"></div>
                  <div className="w-8 h-3 bg-slate-200 rounded"></div>
                </div>
              ))}
            </div>
          ) : (
            <div className="grid grid-cols-2 gap-3">
              {statsCards.map((card, index) => (
                <div
                  key={index}
                  className={`p-3 rounded-xl border ${card.color}`}
                >
                  <card.icon size={20} className="mb-2" />
                  <div className="text-lg font-bold text-theme-text">{card.value}</div>
                  <div className="text-xs text-theme-text-secondary">{card.title}</div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 功能菜单 */}
        <div className="bg-theme-bg rounded-2xl border border-theme-border/60 shadow-sm overflow-hidden">
          <div className="p-5 pb-0">
            <div className="flex items-center gap-2 mb-4">
              <div className="w-1 h-5 bg-gradient-to-b from-blue-500 to-blue-600 rounded-full"></div>
              <h3 className="text-sm font-semibold text-theme-text">功能设置</h3>
            </div>
          </div>
          
          <div className="space-y-0">
            {menuItems.map((item, index) => (
              <button
                key={index}
                onClick={item.onClick}
                className="w-full flex items-center gap-4 p-5 hover:bg-theme-bg-secondary transition-colors text-left border-b border-slate-100 last:border-b-0"
              >
                <div className={`p-2 rounded-xl ${item.color}`}>
                  <item.icon size={20} />
                </div>
                <div className="flex-1">
                  <div className="font-medium text-theme-text">{item.title}</div>
                  <div className="text-sm text-theme-text-muted">{item.subtitle}</div>
                </div>
                <div className="text-slate-400">
                  <ArrowLeft size={16} className="rotate-180" />
                </div>
              </button>
            ))}
          </div>
        </div>

        {/* 版本信息 */}
        <div className="text-center py-4">
          <p className="text-xs text-slate-400">AIDE {getVersionString()}</p>
          <p className="text-xs text-slate-400 mt-1">AI智能任务助手</p>
        </div>
      </main>
    </div>
  )
}
